import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:series_play/utils/sp.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';

class GuestIdHelper {

  GuestIdHelper._();

  static const _key = 'guest_id';

  static Future<String> getGuestId() async {
    // 如果本地已有，直接返回
    final saved = await Sp.getStr(_key);
    if (saved.isNotEmpty) return saved;

    // 设备信息
    final deviceInfo = DeviceInfoPlugin();
    String deviceId = '';
    if (Platform.isAndroid) {
      final info = await deviceInfo.androidInfo;
      deviceId = info.id ?? info.fingerprint ?? '';
    } else if (Platform.isIOS) {
      final info = await deviceInfo.iosInfo;
      deviceId = info.identifierForVendor ?? '';
    } else {
      deviceId = const Uuid().v4();
    }

    // 生成混合唯一 ID
    final randomUuid = const Uuid().v4();
    final combined = '$deviceId-$randomUuid';
    final hash = sha256.convert(utf8.encode(combined)).toString();

    // 保存
    await Sp.putStr(_key, hash);

    return hash;
  }
}
